package dao;

import mode.Message;
import utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 比特就业课
 * @Date 2023-04-02
 */
public class MessageDao {
    /**
     * 往数据库中插入一条记录
     * @param message
     * @return
     */
    public int insert(Message message) {
        // 定义变量
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            // 1. 获取连接
            connection = DBUtil.getConnection();
            // 2. 定义SQL
            String sql = "insert into message_wall values (null, ?, ?, ?)";
            // 3. 获取预处理对象
            statement = connection.prepareStatement(sql);
            // 4. 设置SQL 中的值
            statement.setString(1, message.getSender());
            statement.setString(2, message.getReceiver());
            statement.setString(3, message.getContent());
            // 5. 执行SQL
            int result = statement.executeUpdate();
            // 6. 返回结果
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(null, statement, connection);
        }
        return 0;
    }

    public List<Message> selectAll () {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> result = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from message_wall";
            statement = connection.prepareStatement(sql);
            // 执行SQL
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                if (result == null) {
                    result = new ArrayList<>();
                }
                Message message = new Message();
                message.setSender(resultSet.getString("sender"));
                message.setReceiver(resultSet.getString("receiver"));
                message.setContent(resultSet.getString("content"));
//                message.setSender(resultSet.getString(2));
//                message.setReceiver(resultSet.getString(3));
//                message.setContent(resultSet.getString(4));
                // 把message加入集合
                result.add(message);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(resultSet, statement, connection);
        }
        return result;
    }

}
